package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.common.UUIDGenerator;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.MaintblDataDao;
import com.powerunion.datacollection.model.FormSet;
import com.powerunion.datacollection.model.MaintblData;
import com.powerunion.datacollection.model.SubFormSet;
import com.powerunion.datacollection.model.SubmissionWorkItem;
import com.powerunion.datacollection.model.SysServer;
import com.powerunion.datacollection.model.jsonObject.DBTableField;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.datacollection.service.FormSetManager;
import com.powerunion.datacollection.service.SubFormSetManager;
import com.powerunion.datacollection.util.DBUtil;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class MaintblDataDaoImpl extends JdbcBase implements MaintblDataDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			MaintblDataDaoImpl.class);
	private DBUtil dbUtils = null;

	public MaintblDataDaoImpl() {
		super();
		dbUtils = new DBUtil();
	}

	public boolean save(MaintblData data, String formValues)
			throws DaoException {
		FormSetManager fm = new FormSetManager();
		Connection conn = null;

		try {
			FormSet fs = fm.findFormSetByFormId(data.getFormId());
			SysServer server = fm.getSysServer(fs.getSvrName());
			List fields = this.getMaintblFields(data.getFormId());
			// 把表单值转换成json对象
			JSONObject fieldObject = JSONObject.fromObject(formValues);
			StringBuffer sql = new StringBuffer();
			sql.append(" insert into ").append(fs.getMainTbl()).append("(");

			StringBuffer fieldStr = new StringBuffer();
			fieldStr.append(fs.getKeyFld());
			for (Iterator iter = fields.iterator(); iter.hasNext();) {
				DBTableField f = (DBTableField) iter.next();
				String fieldName = f.getFieldName();
				fieldStr.append(",").append(fieldName);
			}
			sql.append(fieldStr.toString()).append(") values(?");
			StringBuffer valueStr = new StringBuffer();
			for (int i = 0; i < fields.size(); i++) {
				// if(valueStr.toString().equals("")){
				// valueStr.append("?");
				// }else{
				valueStr.append(",").append("?");
				// }
			}
			sql.append(valueStr.toString()).append(")");
			logger.debug("MaintblData sql:" + sql.toString());
			conn = dbUtils.getTblConnection(server);

			StringBuffer delSql = new StringBuffer();
			delSql.append(" delete from ").append(fs.getMainTbl()).append(
					" where ").append(fs.getKeyFld()).append(" = ?");

			this.deleteFormData(data, conn, delSql.toString());

			UpdateOperator update = new UpdateOperator();
			update.setSql(sql.toString());
			update.setUseOnlyConnectionFlag(true);
			update.setPresentConnection(conn);

			String seq = UUIDGenerator.generate4Number();
			data.setFormKey(seq);
			if (fs.getKeyType().toLowerCase().equals("number")) {
				update.addParameter(new SqlParameter(SqlType.BIGINT, new Long(
						Long.parseLong(seq))));
			} else {
				update.addParameter(new SqlParameter(SqlType.VARCHAR, seq));
			}
			for (Iterator iter = fields.iterator(); iter.hasNext();) {
				DBTableField f = (DBTableField) iter.next();
				String fieldName = f.getFieldName();
				String fieldValues = fieldObject.getString(fieldName);
				int fieldType = dbUtils.getSqlTypes(f.getFieldType());
				if (fieldType == SqlType.DATE) {
					Date date = Format.getInstance().stringToDate(fieldValues,
							"yyyy-MM-dd");
					if (date != null) {
						update.addParameter(new SqlParameter(SqlType.DATE,
								new java.sql.Date(date.getTime())));
					} else {
						update.addParameter(new SqlParameter(fieldType, null));
					}
				} else {
					update
							.addParameter(new SqlParameter(fieldType,
									fieldValues));
				}

			}
			if (fields.size() > 0) {
				update.access();
			}

			int effectCount = update.getEffectCounts();
			if (effectCount > 0) {
				if (logger.isDebugEnabled()) {

					logger.debug("save:" + Constants.SAVE + "主表报送信息"
							+ Constants.SUCCESS);
				}
				return this.saveMaintblData(data);
			} else {
				if (logger.isDebugEnabled()) {
					logger.debug("save:" + Constants.SAVE + "主表报送信息"
							+ Constants.FAIL);
				}
				return false;
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存主表报送信息出错！");
		} finally {
			DBUtils.close(conn);
		}

	}

	public boolean saveMaintblData(MaintblData data) throws DaoException {

		StringBuffer sql = new StringBuffer();
		sql.append("insert into dc_maintbl_data(id,form_key,submi_user,")
				.append("proc_id,act_id,form_id) values(?,?,?,?,?,?)");
		UpdateOperator update = new UpdateOperator();
		Connection conn = null;
		try {
			conn = this.getConnection();
			// 先删除原有的记录信息
			this.deleteMaintblData(data, conn);
			update.setUseOnlyConnectionFlag(true);
			update.setPresentConnection(conn);

			update.setSql(sql.toString());
			String id = String.valueOf(this.getSeq("dc_maintbl_data"));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, id));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, data
					.getFormKey()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, data
					.getSubmiUser()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, data
					.getProcId()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, data
					.getActId()));
			update.addParameter(new SqlParameter(SqlType.VARCHAR, data
					.getFormId()));

			update.access();
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("saveMaintblData throw error!");
		} finally {
			DBUtils.close(conn);
		}

		int effect = update.getEffectCounts();
		if (effect > 0) {
			if (logger.isDebugEnabled()) {

				logger.debug("save:" + Constants.SAVE + " MaintblData "
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + " MaintblData "
						+ Constants.FAIL);
			}
			return false;
		}
	}

	public List getMaintblFields(String formId) throws DaoException {
		String sql = "select field_name,field_type,field_label from dc_maintbl_form where form_id=?";
		QueryOperator query = new QueryOperator();
		query.setSql(sql);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, formId));
		List fields = null;

		try {
			fields = new ArrayList();
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int i = 0; i < rs.rowCount; i++) {
					String fieldName = rs.getFieldValueAsString("field_name");
					String fieldType = rs.getFieldValueAsString("field_type");
					String fieldLabel = rs.getFieldValueAsString("field_label");
					DBTableField f = new DBTableField();
					f.setFieldName(fieldName);
					f.setFieldType(fieldType);
					f.setFieldLabel(fieldLabel);

					fields.add(f);
					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("查找表单ID为：" + formId + " 对应的主表字段名出错！");
		}

		return fields;
	}

	/**
	 * 获取主表报送区的报送数据
	 * 
	 * @param data
	 * @return
	 * @throws DaoException
	 */
	public JSONObject getMaintblDataInfo(MaintblData data) throws DaoException {
		Connection conn = null;
		Connection localConnection = null;
		FormSetManager fm = new FormSetManager();
		JSONObject result = new JSONObject();
		try {
			localConnection = this.getConnection();
			FormSet fs = fm.findFormSetByFormId(data.getFormId());
			SysServer server = fm.getSysServer(fs.getSvrName());
			List fields = this.getMaintblFields(data.getFormId());

			conn = dbUtils.getTblConnection(server);

			StringBuffer sql = new StringBuffer();
			sql.append(" select ");

			for (int i = 0; i < fields.size(); i++) {
				DBTableField f = (DBTableField) fields.get(i);
				String fieldName = f.getFieldName();
				sql.append(fieldName);
				if (i != fields.size() - 1) {
					sql.append(",");
				}
			}
			sql.append(" from ").append(fs.getMainTbl()).append(" where ")
					.append(fs.getKeyFld()).append(" =?");
			logger.debug("findMaintblDataByKey sql:" + sql.toString());
			String formKey = this.getMaintblDataByKey(data, localConnection);

			QueryOperator query = new QueryOperator();
			query.setSql(sql.toString());
			query.setUseOnlyConnectionFlag(true);
			query.setPresentConnection(conn);

			query.addParameter(new SqlParameter(SqlType.VARCHAR, formKey));
			query.access();
			if (query.resultSetAvailable()) {

				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());

				if (rs.rowCount > 0) {
					for (Iterator iter = fields.iterator(); iter.hasNext();) {
						DBTableField f = (DBTableField) iter.next();
						String fieldName = f.getFieldName();
						if (f.getFieldType().equals("DATE")) {
							Date fieldValue = rs.getFieldValueAsDate(fieldName);
							String dateStr = Format.getInstance().dateToYMD(
									fieldValue);
							result.put(fieldName, dateStr);
						} else {
							Object fieldValue = rs.getFieldValue(fieldName);
							result.put(fieldName, fieldValue);
						}

					}
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("查找主表报送区数据出错！");
		} finally {
			DBUtils.close(conn);
			DBUtils.close(localConnection);
		}
		return result;
	}

	/**
	 * 获取主从表类型表单的主表报送区数据
	 * 
	 * @param data
	 * @return
	 * @throws DaoException
	 */
	public JSONObject getMaintblDataInfo4SubFormMaintTbl(MaintblData data)
			throws DaoException {
		Connection conn = null;
		Connection localConnection = null;
		SubFormSetManager sfm = new SubFormSetManager();
		JSONObject result = new JSONObject();
		try {
			localConnection = this.getConnection();
			SubFormSet sf = sfm.findFormSetByKey4MaintTbl(data.getFormId());
			SysServer server = sfm.getSysServer(sf.getSvrName());
			List fields = this.getMaintblFields(data.getFormId());

			conn = dbUtils.getTblConnection(server);

			StringBuffer sql = new StringBuffer();
			sql.append(" select ");

			for (int i = 0; i < fields.size(); i++) {
				DBTableField f = (DBTableField) fields.get(i);
				String fieldName = f.getFieldName();
				sql.append(fieldName);
				if (i != fields.size() - 1) {
					sql.append(",");
				}
			}
			sql.append(" from ").append(sf.getTblName()).append(" where ")
					.append(sf.getKeyFld()).append(" =?");
			logger.debug("getMaintblDataInfo4SubFormMaintTbl sql:"
					+ sql.toString());
			String formKey = this.getMaintblDataByKey(data, localConnection);

			QueryOperator query = new QueryOperator();
			query.setSql(sql.toString());
			query.setUseOnlyConnectionFlag(true);
			query.setPresentConnection(conn);

			query.addParameter(new SqlParameter(SqlType.VARCHAR, formKey));
			query.access();
			if (query.resultSetAvailable()) {

				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());

				if (rs.rowCount > 0) {
					for (Iterator iter = fields.iterator(); iter.hasNext();) {
						DBTableField f = (DBTableField) iter.next();
						String fieldName = f.getFieldName();
						if (f.getFieldType().equals("DATE")) {
							Date fieldValue = rs.getFieldValueAsDate(fieldName);
							String dateStr = Format.getInstance().dateToYMD(
									fieldValue);
							result.put(fieldName, dateStr);
						} else {
							Object fieldValue = rs.getFieldValue(fieldName);
							result.put(fieldName, fieldValue);
						}

					}
				}

				rs.clearAll();
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("查找主表报送区数据出错！");
		} finally {
			DBUtils.close(conn);
			DBUtils.close(localConnection);
		}
		return result;
	}

	public String getMaintblDataByKey(MaintblData data, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql
				.append("select form_key from dc_maintbl_data")
				.append(
						"  where submi_user =? and act_id =? and form_id=? and proc_id=? ");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, data
				.getSubmiUser()));
		query.addParameter(new SqlParameter(SqlType.VARCHAR, data.getActId()));
		query.addParameter(new SqlParameter(SqlType.VARCHAR, data.getFormId()));
		query.addParameter(new SqlParameter(SqlType.VARCHAR, data.getProcId()));
		String formKey = "";
		try {
			query.access();
			if (query.resultSetAvailable()) {

				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());

				if (rs.rowCount > 0) {
					formKey = rs.getFieldValueAsString("form_key");
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getMaintblDataByKey throw error!");
		}
		return formKey;
	}

	/**
	 * 提供初始化的表单的外键值 用于填报人第一次填报数据的时候初始化表单
	 * 
	 * @param data
	 * @param conn
	 * @return
	 * @throws DaoException
	 */
	public String getMaintblDataByKey4Init(MaintblData data, Connection conn)
			throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql.append("select form_key from dc_maintbl_data").append(
				"  where proc_id='-1' and act_id ='-1' and form_id=? ");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.setUseOnlyConnectionFlag(true);
		query.setPresentConnection(conn);
		query.addParameter(new SqlParameter(SqlType.VARCHAR, data.getFormId()));
		String formKey = "";
		try {
			query.access();
			if (query.resultSetAvailable()) {

				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());

				if (rs.rowCount > 0) {
					formKey = rs.getFieldValueAsString("form_key");
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getMaintblDataByKey throw error!");
		}
		return formKey;
	}

	private String getMaintblDataByKey(MaintblData data) throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql.append("select form_key from dc_maintbl_data").append(
				"  where submi_user =? and act_id =? and form_id=? ");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());

		query.addParameter(new SqlParameter(SqlType.VARCHAR, data
				.getSubmiUser()));
		query.addParameter(new SqlParameter(SqlType.VARCHAR, data.getActId()));
		query.addParameter(new SqlParameter(SqlType.VARCHAR, data.getFormId()));
		String formKey = "";
		try {
			query.access();
			if (query.resultSetAvailable()) {

				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());

				if (rs.rowCount > 0) {
					formKey = rs.getFieldValueAsString("form_key");
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getMaintblDataByKey throw error!");
		}
		return formKey;
	}

	public List getAllMaintblDataByAct(List submissionWorks)
			throws DaoException {
		// 参数为空
		if (submissionWorks == null || submissionWorks.size() < 1) {
			String[] args = { "submissionWorks" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter submissionWorks NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		Connection conn = null;
		Connection localConnection = null;
		FormSetManager fm = new FormSetManager();
		List maintblDatas = new ArrayList();

		try {
			localConnection = this.getConnection();
			SubmissionWorkItem swi = (SubmissionWorkItem) submissionWorks
					.get(0);
			FormSet fs = fm.findFormSetByFormId(swi.getFormId());
			SysServer server = fm.getSysServer(fs.getSvrName());
			List fields = this.getMaintblFields(swi.getFormId());

			conn = dbUtils.getTblConnection(server);

			StringBuffer sql = new StringBuffer();
			sql.append(" select ");

			for (int i = 0; i < fields.size(); i++) {
				DBTableField f = (DBTableField) fields.get(i);
				String fieldName = f.getFieldName();
				sql.append(fieldName);
				if (i != fields.size() - 1) {
					sql.append(",");
				}
			}
			sql.append(" from ").append(fs.getMainTbl()).append(" where ")
					.append(fs.getKeyFld()).append(" =?");
			logger.debug("getAllMaintblDataByAct sql:" + sql.toString());

			for (Iterator swIter = submissionWorks.iterator(); swIter.hasNext();) {
				SubmissionWorkItem swItem = (SubmissionWorkItem) swIter.next();
				MaintblData mld = new MaintblData();
				mld.setActId(swItem.getId());
				mld.setFormId(swItem.getFormId());
				mld.setSubmiUser(swItem.getStaffId());
				String formKey = this.getMaintblDataByKey(mld, localConnection);

				QueryOperator query = new QueryOperator();
				query.setSql(sql.toString());
				query.setUseOnlyConnectionFlag(true);
				query.setPresentConnection(conn);

				query.addParameter(new SqlParameter(SqlType.VARCHAR, formKey));
				query.access();
				if (query.resultSetAvailable()) {

					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());
					if (rs.rowCount > 0) {
						JSONObject result = new JSONObject();
						for (Iterator iter = fields.iterator(); iter.hasNext();) {
							DBTableField f = (DBTableField) iter.next();
							String fieldName = f.getFieldName();
							if (f.getFieldType().equals("DATE")) {
								Date fieldValue = rs
										.getFieldValueAsDate(fieldName);
								String dateStr = Format.getInstance()
										.dateToYMD(fieldValue);
								result.put(fieldName, dateStr);
							} else {
								Object fieldValue = rs.getFieldValue(fieldName);
								result.put(fieldName, fieldValue);
							}

						}
						maintblDatas.add(result);
					}
					rs.clearAll();
				}
			}

		} catch (Exception e) {
			logger.error("getAllMaintblDataByAct throw error!", e);
			throw new DaoException("查找环节所有的主表报送区数据出错！");
		} finally {
			DBUtils.close(conn);
			DBUtils.close(localConnection);
		}

		return maintblDatas;
	}

	public boolean deleteMaintblData(MaintblData data, Connection conn)
			throws DaoException {
		String sql = "delete from dc_maintbl_data where submi_user=? and proc_id=? and form_id=? and act_id=? ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);
		update.addParameter(new SqlParameter(SqlType.VARCHAR, data
				.getSubmiUser()));
		update
				.addParameter(new SqlParameter(SqlType.VARCHAR, data
						.getProcId()));
		update
				.addParameter(new SqlParameter(SqlType.VARCHAR, data
						.getFormId()));
		update.addParameter(new SqlParameter(SqlType.VARCHAR, data.getActId()));
		try {
			update.access();
		} catch (Exception e) {
			logger.error("删除主表信息出错！", e);
			throw new DaoException("删除表信息出错！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:删除表信息" + Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:删除表信息" + Constants.FAIL);
			}
			return false;
		}

	}

	public boolean deleteFormData(MaintblData data, Connection conn, String sql)
			throws DaoException {

		String formKey = this.getMaintblDataByKey(data);

		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);
		update.setUseOnlyConnectionFlag(true);
		update.setPresentConnection(conn);
		update.addParameter(new SqlParameter(SqlType.VARCHAR, formKey));

		try {
			update.access();
		} catch (Exception e) {
			logger.error("删除业务表信息出错！", e);
			throw new DaoException("删除业务表信息出错！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:删除业务表信息出错" + Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:删除业务表信息出错" + Constants.FAIL);
			}
			return false;
		}
	}

	public List getAllMaintblDataByAct4subTbl(List submissionWorks)
			throws DaoException {
		// 参数为空
		if (submissionWorks == null || submissionWorks.size() < 1) {
			String[] args = { "submissionWorks" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter submissionWorks NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		Connection conn = null;
		Connection localConnection = null;
		//FormSetManager fm = new FormSetManager();
		List maintblDatas = new ArrayList();

		try {
			localConnection = this.getConnection();
			SubmissionWorkItem swi = (SubmissionWorkItem) submissionWorks
					.get(0);
			SubFormSetManager sfsm = new SubFormSetManager();
			SubFormSet sfs = sfsm.findFormSetByKey4MaintTbl(swi.getFormId());
			SysServer server = sfsm.getSysServer(sfs.getSvrName());
			List fields = this.getMaintblFields(swi.getFormId());

			conn = dbUtils.getTblConnection(server);

			StringBuffer sql = new StringBuffer();
			sql.append(" select ");

			for (int i = 0; i < fields.size(); i++) {
				DBTableField f = (DBTableField) fields.get(i);
				String fieldName = f.getFieldName();
				sql.append(fieldName);
				if (i != fields.size() - 1) {
					sql.append(",");
				}
			}
			sql.append(" from ").append(sfs.getTblName()).append(" where ")
					.append(sfs.getKeyFld()).append(" =?");
			logger.debug("getAllMaintblDataByAct sql:" + sql.toString());

			for (Iterator swIter = submissionWorks.iterator(); swIter.hasNext();) {
				SubmissionWorkItem swItem = (SubmissionWorkItem) swIter.next();
				MaintblData mld = new MaintblData();
				mld.setActId(swItem.getId());
				mld.setFormId(swItem.getFormId());
				mld.setSubmiUser(swItem.getStaffId());
				mld.setProcId(swItem.getProcId());
				String formKey = this.getMaintblDataByKey(mld, localConnection);

				QueryOperator query = new QueryOperator();
				query.setSql(sql.toString());
				query.setUseOnlyConnectionFlag(true);
				query.setPresentConnection(conn);

				query.addParameter(new SqlParameter(SqlType.VARCHAR, formKey));
				query.access();
				if (query.resultSetAvailable()) {

					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());
					if (rs.rowCount > 0) {
						JSONObject result = new JSONObject();
						for (Iterator iter = fields.iterator(); iter.hasNext();) {
							DBTableField f = (DBTableField) iter.next();
							String fieldName = f.getFieldName();
							if (f.getFieldType().equals("DATE")) {
								Date fieldValue = rs
										.getFieldValueAsDate(fieldName);
								String dateStr = Format.getInstance()
										.dateToYMD(fieldValue);
								result.put(fieldName, dateStr);
							} else {
								Object fieldValue = rs.getFieldValue(fieldName);
								result.put(fieldName, fieldValue);
							}

						}
						maintblDatas.add(result);
					}
					rs.clearAll();
				}
			}

		} catch (Exception e) {
			logger.error("getAllMaintblDataByAct throw error!", e);
			throw new DaoException("查找环节所有的主表报送区数据出错！");
		} finally {
			DBUtils.close(conn);
			DBUtils.close(localConnection);
		}

		return maintblDatas;
	}

}
